package com.zhx.listener;

import com.zhx.domain.User;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Hashtable;
import java.util.Map;

/**
 * 监听访问系统的用户
 * @program: web-springboot
 * @author: zhx
 * @create: 2021-05-23 13:02
 **/
@WebListener
public class UserListener implements HttpSessionListener {

    //当用户和服务器session交互的时候，触发这个方法
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        String id = session.getId();
        ServletContext servletContext = session.getServletContext();
        if(session.isNew()){
            String username = "游客";
            Map<String, String> online = (Map<String, String>) servletContext.getAttribute("online");
            if (online==null){
                online = new Hashtable<String,String>();
            }
            online.put(id, username);
            servletContext.setAttribute("online", online );
        }
    }

    //当用户和服务器的session断开的时候，触发这个方法
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        String id = session.getId();
        ServletContext servletContext = session.getServletContext();
        Map<String,String> online = (Map<String, String>) servletContext.getAttribute("online");
        if (online!=null){
            online.remove(id);
        }
        servletContext.setAttribute("online",online );

    }
}
